package cn.kzgg.ymcc.listener;

import cn.kzgg.ymcc.domain.CourseOrder;
import cn.kzgg.ymcc.service.ICourseOrderService;
import com.alibaba.fastjson.JSON;
import dto.PayDto;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

@Component
@RocketMQTransactionListener(txProducerGroup = "service-order-producer")//和发送事务消息指明的名字一致
@Slf4j
public class CourseOrderRocketMqListener implements RocketMQLocalTransactionListener {

    @Autowired
    private ICourseOrderService courseOrderService;

    /**
     * 发送事务消息
     *      发送主订单和子订单
     * @param message
     * @param o
     * @return
     */
    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object o) {
        //保存本地事务
        log.info("保存本地事务");
        if(o==null){
            //直接回滚
            return RocketMQLocalTransactionState.ROLLBACK;
        }
        try {
            CourseOrder courseOrder = (CourseOrder) o;
            //直接保存主订单和子订单
            courseOrderService.saveCourseOrderAndItems(courseOrder);
        } catch (Exception e) {
            e.printStackTrace();
            return RocketMQLocalTransactionState.ROLLBACK;
        }
        return RocketMQLocalTransactionState.COMMIT;
    }

    /**
     *检查本地事务
     *      检查主订单和子订单是否保存成功
     * @param message
     * @return
     */
    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        log.info("检查本地事务状态");
        try {
            //检查本地事务状态
            byte[] byteMsg = (byte[]) message.getPayload();
            String strMsg = new String(byteMsg, StandardCharsets.UTF_8);
            PayDto payDto = JSON.parseObject(strMsg, PayDto.class);
            CourseOrder courseOrder = courseOrderService.selectByOrderSn(payDto.getOrderNo());
            return courseOrder==null?RocketMQLocalTransactionState.ROLLBACK:RocketMQLocalTransactionState.COMMIT;
        } catch (Exception e) {
            e.printStackTrace();
            return RocketMQLocalTransactionState.ROLLBACK;
        }
    }
}
